package com.hzg.stream.demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author: huangzhigao
 * @Date: 2022/4/18 19:02
 */
public class WordCountDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        String wordPath = WordCountDemo.class.getClassLoader().getResource("wordCount.txt").getPath();
        DataStreamSource<String> source = env.readTextFile(wordPath);
        source.flatMap((FlatMapFunction<String, Tuple2<String, Integer>>) (s, collector) -> {
            String[] split = s.split("\n");
            collector.collect(new Tuple2<>(split[0], 1));
        }).returns(Types.TUPLE(Types.STRING, Types.INT)).keyBy((KeySelector<Tuple2<String, Integer>, Object>) stringIntegerTuple2 -> stringIntegerTuple2.f0).sum(1).print();

        source.shuffle();
        env.execute();

    }
}
